package yl.hs.bmipfull.controllers.material;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yl.hs.bmipfull.annotations.Excel;
import yl.hs.bmipfull.controllers.ControllerBase;
import yl.hs.bmipfull.daos.material.IPurchaseContractDao;
import yl.hs.bmipfull.daos.material.IPurchaseContractProductDao;
import yl.hs.bmipfull.pojo.material.PurchaseReceiptEntity;
import yl.hs.bmipfull.service.material.IPurchaseContractProductService;
import yl.hs.bmipfull.service.material.IPurchaseReceiptService;
import yl.hs.bmipfull.service.system.ISearchViewService;
import yl.hs.bmipfull.utils.ExcelUtil;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.SubmitModel;
import yl.hs.bmipfull.viewmodels.WebResult;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作用:  采购产品单据信息控制层<br/>
 * 创建时间: 2021年05月19日 17时26分05秒 <br/>
 *
 * @author 吴高丰
 */
@Api(value = "采购产品单据信息Web接口", tags = "采购管理——采购产品单据信息操作")
@RequestMapping(value = "/api/purchase/receipt")
@RestController
public class PurchaseReceiptController extends ControllerBase {

    @Autowired
    IPurchaseReceiptService service;

    @Autowired
    ISearchViewService svSVC;
    @Autowired
    IPurchaseContractProductService purchaseContractProductService;
    @Autowired
    IPurchaseContractDao purchaseContractDao;

    @ApiOperation(value = "查询采购产品单据信息", notes = "查询采购产品单据信息")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public WebResult queryList(@ApiParam(value = "查询条件") @RequestBody PageQuery pageQuery) {
        try {
            return success("查询成功", service.queryList(pageQuery));
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "查询产品信息价", notes = "分页查询查询产品信息价")
    @RequestMapping(value = "/averagepriceofmaterials/{rowNum}/{page}", method = RequestMethod.POST)
    public WebResult averagePriceOfMaterials(@RequestBody PageQuery query,
                                             @ApiParam(value = "页码") @PathVariable int page,
                                             @ApiParam(value = "每页条数") @PathVariable int rowNum) {
        try {
            var result = service.averagePriceOfMaterials(query, page, rowNum);
            return success("查询成功", result);
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "查询采购产品单据信息", notes = "分页查询采购产品单据信息")
    @RequestMapping(value = {"/{rowNum}/{page}", "/{rowNum}/{page}/{productCateSn}"}, method = RequestMethod.POST)
    public WebResult queryPage(@RequestBody PageQuery query,
                               @ApiParam(value = "页码") @PathVariable int page,
                               @ApiParam(value = "每页条数") @PathVariable int rowNum, @ApiParam(value = "使用产品sn") @PathVariable(required = false) String productCateSn) {
        try {

            var result = service.queryPage(query, rowNum, page, productCateSn);
            query.getQuery().put("productCateSn", productCateSn);
            val pur = service.queryPage(query, 100000, 1, productCateSn).getData();
            var reviewWeight = pur.stream().mapToDouble(s -> Double.valueOf((s.getGrossWeight() == null ? 0 : s.getGrossWeight()).toString())).sum();
            var netWeight = pur.stream().mapToDouble(s -> Double.valueOf((s.getNetWeight() == null ? 0 : s.getNetWeight()).toString())).sum();
            var amount = pur.stream().mapToDouble(s -> Double.valueOf((s.getAmount() == null ? 0 : s.getAmount()).toString())).sum();
            var unloadingMoney = pur.stream().mapToDouble(s -> Double.valueOf((s.getUnloadingMoney() == null ? 0 : s.getUnloadingMoney()).toString())).sum();
            Map<String, Object> stringObjectMap = Tl.toMap(result);
            stringObjectMap.put("reviewWeight", reviewWeight);
            stringObjectMap.put("netWeight", netWeight);
            stringObjectMap.put("unloadingMoney", unloadingMoney);
            stringObjectMap.put("amount", amount);

            return success("ok", stringObjectMap);
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "查询采购产品单据信息", notes = "根据采购产品单据信息编号查询采购产品单据信息")
    @RequestMapping(value = "/{sn}", method = RequestMethod.GET)
    public WebResult findBySn(@ApiParam(value = "编号") @PathVariable String sn) {
        return success("查询成功", service.findBySn(sn));
    }

    @ApiOperation(value = "保存采购产品单据信息", notes = "查询/更新采购产品单据信息信息")
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public WebResult saveMenu(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        Integer result;
        try {
            result = service.savePurchaseReceipt(submitModel.getData(), submitModel.getSn());
            if (result > 0) {
                return success("保存成功");
            } else {
                return fail("数据未保存");
            }
        } catch (Exception e) {
            return error(e);
        }

    }

    @ApiOperation(value = "删除采购产品单据信息信息", notes = "根据采购产品单据信息编号删除系采购产品单据信息信息")
    @RequestMapping(path = "", method = RequestMethod.DELETE)
    public WebResult delete(@ApiParam(value = "采购产品单据信息编号", name = "sn", allowMultiple = true, required = true) @RequestParam("sn") String[] sn) {
        if (service.delete(sn) > 0) {
            return success("删除成功");
        } else {
            return fail("删除失败");
        }

    }

    @ApiOperation(value = "作废入库单", notes = "作废入库单")
    @RequestMapping(path = "invalid/{sn}", method = RequestMethod.POST)
    public WebResult invalidOrder(@PathVariable String sn, @RequestParam String cause) {
        try {
            var result = service.invalidOrder(sn, cause);
            if (result > 0) {
                return success("作废成功");
            } else {
                return fail("作废失败");
            }
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "恢复入库单", notes = "恢复入库单")
    @PostMapping("restore/{sn}")
    public WebResult restoreOrder(@PathVariable String sn, @RequestParam String cause) {
        try {
            var result = service.restore(sn, cause);
            if (result > 0)
                return success("单据已恢复");
            else {
                return fail("恢复失败");
            }
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "保存审核信息", notes = "保存发货单审核信息")
    @RequestMapping(path = "review/orders", method = RequestMethod.POST)
    public WebResult saveReviewOrders(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        List<Map<String, Object>> datas = (List<Map<String, Object>>) submitModel.getData().get("orders");
        try {
            int result = 0;
            if (datas != null && datas.size() > 0) {
                for (var map : datas) {
                    SubmitModel submitModelObj = new SubmitModel();
                    submitModelObj.setSn((String) map.get("sn"));
                    submitModelObj.setData((Map<String, Object>) map.get("data"));
                    result += result = service.saveReviewOrders(submitModelObj);
                }
            }

            if (result > 0) {
                return success("审核完成");
            } else {
                return fail("审核失败");
            }
        } catch (Exception e) {
            return error(e);
        }
    }

    @ApiOperation(value = "保存审核信息", notes = "保存发货单审核信息")
    @RequestMapping(path = "review", method = RequestMethod.POST)
    public WebResult saveReview(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        Integer result = null;
        try {
            result = service.saveReviewOrders(submitModel);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (result > 0) {
            return success("审核完成");
        } else {
            return fail("审核失败");
        }
    }
    @ApiOperation(value = "保存装卸费审核信息", notes = "保存装卸费审核信息")
    @RequestMapping(path = "unloadingreview", method = RequestMethod.POST)
    public WebResult saveunloadingReview(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        Integer result = null;
        try {
            result = service.updateUnloading(submitModel);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (result > 0) {
            return success("审核完成");
        } else {
            return fail("审核失败");
        }
    }
    @ApiOperation(value = "保存重量数量核对信息", notes = "保存发货单重量数量核对信息")
    @RequestMapping(path = "weightCheck", method = RequestMethod.POST)
    public WebResult saveWeightCheck(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        try {
            var result = service.saveWeightCheck(submitModel);
            if (result > 0) {
                return success("数据已保存");
            } else {
                return fail("调整失败");
            }
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "保存审核备注信息", notes = "保存发货单审核备注信息")
    @RequestMapping(path = "reviewFlag", method = RequestMethod.POST)
    public WebResult saveReviewFlag(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        try {
            var result = service.saveReviewFlag(submitModel);
            if (result > 0) {
                return success("保存成功");
            } else {
                return fail("保存失败");
            }
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "根据入库单编号修改状态", notes = "根据入库单编号修改发货单状态")
    @RequestMapping(value = "changeStateBySn/{sn}/{state}", method = RequestMethod.GET)
    @ResponseBody
    public WebResult changeStateBySn(@PathVariable String sn, @PathVariable short state) {
        try {
            Integer result = 0;
            if (state == 0) {
                result = service.changeStateBySN(sn.split(","), (short) 1);
            } else {
                result = service.changeStateBySN(sn.split(","), state);
            }
            if (result > 0) {
                return success("数据已修改");
            } else if (result == -2) {
                return fail("数据修改失败！");
            }
            return fail("没有修改的任何数据");
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "导出原材入库数据", notes = "导出原材入库数据")
    @RequestMapping(path = "/export", method = RequestMethod.POST)
    public void exportOrders(HttpServletResponse response) {
        try {


            PageQuery pageQuery = new PageQuery();
            pageQuery.getQuery().put("key", "");
            var list = service.queryList(pageQuery);
            ExcelUtil<PurchaseReceiptEntity> util = new ExcelUtil<PurchaseReceiptEntity>(PurchaseReceiptEntity.class);

//            response.setContentType("application/vnd.ms-excel;charset=utf-8");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-disposition", "attachment;filename=" + new String( "原材入库信息".getBytes("gb2312"), "ISO8859-1" ) + ".xls");
            //ExcelUtil.download(response, list, PurchaseReceiptEntity.class, "原材入库信息");
            //ExcelUtil.export2Web(response, "原材入库信息", "原材入库信息", Test.class,list);
            // util.init(list,"原材入库信息", Excel.Type.EXPORT);
            //util.ex
        } catch (Exception ee) {
            error(ee);
        }
    }

    @ApiOperation(value = "获取入库单时间分组信息", notes = "获取入库单时间 分组信息")
    @GetMapping("/set-time-group")
    public WebResult getSetTimeGroup() {
        return success("ok", service.getSetTime());
    }

    @ApiOperation(value = "主机入库状态操作接口", notes = "主机入库状态操作接口")
    @PutMapping("/inhost/{state}/{sn}")
    public WebResult changeInHost(@PathVariable int state, @PathVariable String sn) {
        try {
            var result = service.changeInHost(state, sn);
            return success((state == 0 ? "取消入库" : "入库") + "已完成");
        } catch (Exception ee) {
            return error(ee);
        }
    }

    @ApiOperation(value = "根基y原材信息查询供应商", notes = "根基y原材信息查询供应商")
    @GetMapping("/selectContract/{sn}")
    public WebResult updateContract(@PathVariable String sn) {
        try {
            var result = purchaseContractProductService.quantityByProductSN(sn);
            var list = result.stream().map(t -> t.getContractSn()).toList();
            var contract = purchaseContractDao.quantityByListSN(list);
            return success("查询成功", contract);
        } catch (Exception ee) {
            return error(ee);
        }
    }
    @ApiOperation(value = "根据信息更改供应商", notes = "根据信息更改供应商")
    @GetMapping("/updateContract/{sn}/{contractsn}")
    public WebResult UpdateContract(@PathVariable String sn, @PathVariable String contractsn) {
        var order = service.findBySn(sn);
        var result = 0;
        if (order != null) {
            var contract = purchaseContractDao.findBySN(contractsn);
            if (contract != null) {
                order.setContractSN(contract.getSn());
                order.setContractingUnit(contract.getContractingUnit());
                order.setSupplierName(contract.getSupplierName());
                order.setSupplierSN(contract.getSupplierSN());
                order.setSupplierNamePY(contract.getSupplierNamePY());
                result = service.update(order);
            }
        }
        if (result > 0) {
            return success("更改成功");
        } else {
            return fail("更改失败");
        }
    }
    @ApiOperation(value = "根据信息更改供应商", notes = "根据信息更改供应商")
    @GetMapping("/updatenetweight/{sn}/{blockWeight}/{orgWeight}")
    public WebResult updateNetweight(@PathVariable String sn, @PathVariable BigDecimal blockWeight,@PathVariable BigDecimal orgWeight) {
        var result =  service.updateNetWeightBuSN(sn,blockWeight,orgWeight);
        if (result > 0) {
            return success("更改成功");
        } else {
            return fail("更改失败");
        }
    }
    @ApiOperation(value = "保存运费审核信息", notes = "保存入库单运费审核信息")
    @RequestMapping(path = "reviewFreight", method = RequestMethod.POST)
    public WebResult saveReviewFreight(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        if (service.FreightReviewOrders(submitModel) > 0) {
            return success("审核完成");
        } else {
            return fail("审核失败");
        }
    }

    @ApiOperation(value = "入库单运费批量审核", notes = "入库单运费批量审核")
    @RequestMapping(path = "reviewFreightList", method = RequestMethod.POST)
    public WebResult saveReviewFreightList(@ApiParam(value = "提交信息") @RequestBody SubmitModel submitModel) {
        Integer result = 0;
        try {
            List<Map<String, Object>> data = (List<Map<String, Object>>) submitModel.getData().get("orders");
            if (data != null && data.size() > 0) {
                for (var map : data) {
                    SubmitModel submitModelObj = new SubmitModel();
                    submitModelObj.setSn((String) map.get("sn"));
                    submitModelObj.setData((Map<String, Object>) map.get("data"));
                    result += service.FreightReviewOrders(submitModelObj);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (result > 0) {
            return success("审核完成");
        } else {
            return fail("审核失败");
        }
    }
}